package com.vmladenov.cook.core.adapters;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.vmladenov.cook.R;
import com.vmladenov.cook.core.Helpers;
import com.vmladenov.cook.core.db.ProductsRepository;
import com.vmladenov.cook.core.html.SmallPreview;

public class SearchProductAndSpiceAdapter extends ArrayAdapter<SmallPreview> implements Filterable
{
	ProductsRepository repository;
	ArrayList<SmallPreview> data;
	LayoutInflater inflater;

	public SearchProductAndSpiceAdapter(Context context)
	{
		super(context, android.R.layout.simple_dropdown_item_1line);
		repository = Helpers.getDataHelper().ProductsRepository;
		inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount()
	{
		return data.size();
	}

	@Override
	public SmallPreview getItem(int index)
	{
		return data.get(index);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View v = convertView;
		if (v == null)
		{
			v = inflater.inflate(R.layout.text_view_item, null);
		}
		SmallPreview preview = getItem(position);
		TextView txtView = (TextView) v;
		txtView.setText(preview.title);
		txtView.setTextColor(Color.BLACK);
		return v;
	}

	@Override
	public Filter getFilter()
	{
		return new Filter()
		{
			@Override
			protected FilterResults performFiltering(CharSequence constraint)
			{
				FilterResults filterResults = new FilterResults();
				if (constraint != null)
				{
					data = repository.getProductsAndSpices(constraint.toString());
					filterResults.values = data;
					filterResults.count = data.size();
				}
				return filterResults;
			}

			@Override
			protected void publishResults(CharSequence contraint, FilterResults results)
			{
				if (results != null && results.count > 0)
				{
					notifyDataSetChanged();
				}
				else
				{
					notifyDataSetInvalidated();
				}
			}
		};
	}
}
